package com.example.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.User;
import com.example.exception.BusinessException;
import com.example.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    List<String> ALL_PERMISSIONS = List.of("USER", "ADMIN", "SUPER_ADMIN");

    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名从数据库中查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(username != null, User::getUsername, username));
        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        if(user.getStatus() == 0){
            throw new BusinessException("用户已被禁用");
        }
        int role = user.getRole();

        log.info("role:{}",role);

        List<String> permissions = null;
        if (role == 1){
            permissions = ALL_PERMISSIONS;
        }else if (role == 2){
            permissions = List.of("USER", "ADMIN");
        }else if (role == 3){
            permissions = List.of("USER");
        }
        return new LoginUser(user,permissions);
    }
}